package com.wootion.dizhi.utils;
import com.alibaba.druid.pool.DruidDataSource;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class SqlExporter {
    private  final Connection connection;

    public SqlExporter(DruidDataSource druidDataSource) throws SQLException {
        connection = druidDataSource.getConnection().getConnection();
    }

    public void export(String[] tableNames,String outputPath){
        for (int i = 0; i < tableNames.length; i++) {
            String insertDataSql = this.getInsertDataSql(tableNames[i]);
            try {
//                FileWriter fileWriter = new FileWriter(outputPath,true);
//                fileWriter.write(insertDataSql);
//                fileWriter.close();
                BufferedWriter writer = new BufferedWriter (new OutputStreamWriter (new FileOutputStream (outputPath,true), StandardCharsets.UTF_8));
                writer.write(insertDataSql);
                writer.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

    }

    public String getInsertDataSql(String tableName){
        String query = "select * from " + tableName;
        try {
            Statement statement = connection.createStatement();
            ResultSet resultSet = statement.executeQuery(query);
            StringBuilder sqlBuilder = new StringBuilder();
            while (resultSet.next()){
                sqlBuilder.append("insert into ").append(tableName).append(" values (");
                int columnCount = resultSet.getMetaData().getColumnCount();
                for (int i = 1 ; i <= columnCount; i++) {
                    sqlBuilder.append("'").append(resultSet.getString(i)).append("'");
                    if(i < columnCount){
                        sqlBuilder.append(", ");
                    }
                }
                sqlBuilder.append(");\n");
            }
            return sqlBuilder.toString();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
